/* eslint-disable semi */
/**
 * 折线图
 * 说明：能适应单指标、多指标的展示（考虑多指标时可以转变为多条折线图）
 * data = [{
       id: 'line',
       name: '折线图',
       regioncode: "aaa",
       regionname: "aaa",
       lon: "70.92866163503169",
       lat: "78.830660058696104",
       width: '100px',
       height: '100px',
       showThumbnails: true,//是否展示图例控件，默认展示
       x: ['周一', '周二', '周三', '周四', '周五', '周六', '周末'],
       data: [{
         name: '邮件营销',
         type: 'line',
         data: [120, 132, 101, 134, 90, 230, 210]
       }, {
         name: '联盟广告',
         type: 'line',
         data: [220, 182, 191, 234, 290, 330, 310]
       }, {
         name: '视频广告',
         type: 'line',
         data: [150, 232, 201, 154, 190, 330, 410]
       }, {
         name: '直接访问',
         type: 'line',
         data: [320, 332, 301, 334, 390, 330, 320]
       }, {
         name: '搜索引擎',
         type: 'line',
         data: [820, 932, 901, 934, 1290, 1330, 1320]
       }]
     }]
 *
 */
import echarts from 'echarts'; // echarts 文件引入
import styleModify from './echarts.stylemodify'; // 设置图层的可见性，透明度，zIndex文件引入
import colorPicker from './echarts.colorpicker'; // 颜色初始化配置文件
import sgisLayerBase from '../../sgis.layer.base';
export default {
  activeMap: {}, // 当前活动地图
  lineLayer: {},
  lineLayerInfo: {}, // 图层其他相关信息
  charts: [], // 所有echart图层记录
  graph: [], // 初始化图例颜色
  /**
   * 创建地图折形图专题图
   */
  createLayer(map, data) {
    if (!map) {
      return;
    }
    if (!data || !data.data.length) {
      return;
    }
    this.activeMap = map;
    const lineMarkers = this.createMarker(data.data); // 创建好所有marker
    const lineLayer = L.layerGroup(lineMarkers)
      .addTo(map);
    styleModify.onZoom(this.activeMap, lineMarkers); // 为markers绘图添加缩放监听改变z-Index，由于marker的zIndex会随着纬度变化而变化;
    // 设置容器初始ZINdex,为后面调整图层顺序功能 开始
    // 此处必须先把容器加到地图上才能加载图表
    this.lineLayer = lineLayer;
    // 将容器加载到地图容器
    this.createCharts(lineMarkers, data.data);
    const id = "line_chart_" + data.id + "_" + new Date().getTime()
    // 设置自定义颜色
    styleModify.setLayerOrder(styleModify.curZindex, lineLayer._layers, id);
    // 设置容器初始ZINdex,为后面调整图层顺序功能 结束
    styleModify.layerOrder[id] = styleModify.curZindex;
    styleModify.curZindex -= 1;
    lineLayer.setCustomColor = this.setCustomColor; // 图例颜色随着自定义颜色改变而改变
    lineLayer.setOpacity = styleModify.setOpaticty; // 设置图层透明度
    lineLayer.setVisible = styleModify.setVisible; // 设置图层透明度
    lineLayer.setZIndexOffset = this.setZIndexOffset; // 设置调整图层顺序函数;
    lineLayer.autoCalgraph = this.autoCalgraph;
    lineLayer.calSeries = this.calSeries;
    lineLayer.charts = { ...this.charts
    };
    lineLayer.layerId = id;
    this.clickLineIcon(); // 添加切换堆叠图功能
    const lineLayerInfo = {
      layerId: id,
      name: data.name,
      type: "line",
      layer: lineLayer,
      show: data.showThumbnails !== false,
      html: this.calgraph(id)

    };
    this.lineLayerInfo = lineLayerInfo;
    sgisLayerBase.setOverLayers(lineLayerInfo);
    return lineLayerInfo;
  },
  /**
   * 创建echarts容器
   */
  createMarker(datas) {
    const resultMarkers = [];
    for (let i = 0; i < datas.length; i++) {
      const data = datas[i];
      const time = +new Date();
      // 初始化最小宽高开始
      let width = colorPicker.size;
      if (data.hasOwnProperty('width')) {
        width = data.width.slice(0, -2);
        width = parseInt(width);
        if (width < colorPicker.size) {
          width = colorPicker.size;
        }
      }
      let height = colorPicker.size;
      if (data.hasOwnProperty('height')) {
        height = data.width.slice(0, -2);
        height = parseInt(height);
        if (height < colorPicker.size) {
          height = colorPicker.size;
        }
      }
      const iconWidth = width + 35;
      const iconHeight = height + 35;
      // 初始化最小宽高结束
      const chartMarker = L.marker([data.lat, data.lon], {
        id: "line_chart_" + i + time, // 生成id
        pane: styleModify.pane, // 为设置自定义的图层顺序特别设定
        icon: L.divIcon({
          className: "leaflet-echart-icon",
          iconSize: [iconWidth, iconHeight],
          html: `
           <div style ="box-sizing:border-box;position:relative;z-index:'99999';width:${iconWidth}px;height:${iconHeight}px" >
          <i class = 'iconfont icon-Refresh' style="position:absolute;right:0px;top:35px;color:${colorPicker.line.axisColor};" reset='line_chart_${i}${time}' title='还原'></i>
          <i class = 'iconfont icon-duidietu'
          style = "position:absolute;right:25px;top:35px;color:${colorPicker.line.axisColor}" line='line_chart_${i}${time}' title='堆叠图'></i>
          <div id="line_chart_${i}${time}" style="width:${width}px;height:${height}px;position:relative;background-color:transparent;z-index='99999'"></div>
          </div>`
        })
      });
      resultMarkers.push(chartMarker);
    }

    return resultMarkers;
  },
  /**
   * 创建图表
   * @param {Object} lineMarkers 图表容器
   * @param {Object} datas 数据
   */
  createCharts(lineMarkers, datas) {
    for (let i = 0; i < datas.length; i++) {
      const chart = echarts.init(document.getElementById(lineMarkers[i].options.id));
      const chartOption = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        color: colorPicker.color,
        grid: {
          left: "3%",
          right: "8%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [{
          type: "category",
          axisLine: {
            lineStyle: {
              color: colorPicker.line.axisColor
            }
          },
          data: datas[i].x, // 设置x轴坐标
          boundaryGap: false,
          axisTick: {
            alignWithLabel: true
          },
          axisLabel: {
            color: colorPicker.line.axisColor
          }
        }],
        yAxis: [{
          axisLabel: {
            color: colorPicker.line.axisColor
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: colorPicker.line.axisColor
            }
          },
          splitLine: {
            show: false
          }
        }],
        series: this.calSeries(datas[i].data)
      };
      chart.setOption(chartOption);
      this.charts.push({
        id: lineMarkers[i].options.id,
        echart: chart
      });
    }
  },
  /* *
   * echarts右侧按钮添加点击事件
   */
  clickLineIcon() {
    const els = document.querySelectorAll('i[line]');
    for (let i = 0; i < els.length; i++) {
      const el = els[i];
      el.onclick = () => {
        const id = el.getAttribute('line');
        for (const key in this.charts) {
          if (this.charts[key].id === id) {
            const options = this.charts[key].echart.getOption();
            let series = options.series;
            series = this.calSeries(series, 'stack');
            options.series = series;
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成堆叠图
    const els_r = document.querySelectorAll('i[reset]');
    for (let i = 0; i < els_r.length; i++) {
      const el = els_r[i];
      el.onclick = () => {
        const id = el.getAttribute('reset');
        for (const key in this.charts) {
          if (this.charts[key].id === id) {
            const options = this.charts[key].echart.getOption();
            let series = options.series;
            series = this.calSeries(series, 'line');
            options.series = series;
            this.charts[key].echart.clear();
            this.charts[key].echart.setOption(options);
            return;
          }
        }
      };
    }
    // 变换成折线图
  }, // 堆叠图切换
  /**
   * @param {object} {
       lineStyle: ["red", "green", "skyblue", "yellow", "tomato"],
       axisStyle: this.color1,
       axisLableStyle: this.color1
     }
   */
  setCustomColor(layers, pars) {
    const par = {
      ...pars,
      lineStyle: pars.colors
    };
    for (const key in layers.charts) {
      const item = layers.charts[key];
      const option = item.echart.getOption();
      // 设置x轴与y轴颜色 开始
      if (par.hasOwnProperty('axisStyle')) {
        option.xAxis = {
          ...option.xAxis,
          axisLine: {
            show: true,
            lineStyle: {
              color: par.axisStyle
            }
          }
        };
        option.yAxis = {
          ...option.yAxis,
          axisLine: {
            show: true,
            lineStyle: {
              color: par.axisStyle
            }
          }
        };
      }
      // 设置x轴与y轴颜色 结束
      // 设置x轴与y轴文字颜色开始
      if (par.hasOwnProperty('axisLableStyle')) {
        option.xAxis = {
          ...option.xAxis,
          axisLabel: {
            color: par.axisLableStyle
          }
        };
        option.yAxis = {
          ...option.yAxis,
          axisLabel: {
            color: par.axisLableStyle
          }
        };
      }
      // 设置x轴与y轴文字颜色结束
      // 设置折线颜色开始
      if (par.hasOwnProperty('lineStyle')) {
        option.color = par.lineStyle;
        let data = option.series;
        data = layers.calSeries(data, 'colors', par.lineStyle);
        option.series = data;
      }
      // 设置折线颜色结束
      item.echart.setOption(option);
      // 修改图例颜色
      layers.autoCalgraph(layers.layerId, pars.colors);
    }
  }, // 设置自定义颜色函数
  /* *格式化数据
   * lengend
   */
  calLend(datas) {
    const ledend = [];
    for (const item of datas.data) {
      ledend.push(item.name);
    }
    return ledend;
  },
  /* *格式化数据
   */
  calSeries(data, stack, colors) {
    this.graph = []
    for (const key in data) {
      const index = key % colorPicker.line.color.length;
      const color = colors && colors[key] ? colors[key] : (data[key].color ? data[key].color : colorPicker.line.color[index]);
      this.graph.push({
        color,
        name: data[key].name
      });
      data[key] = {
        ...data[key],
        lineStyle: {
          color
        },
        symbol: 'pin'
      };
      // /堆叠图配置开始
      if (stack === 'stack') {
        data[key] = {
          ...data[key],
          stack: '总量',
          areaStyle: {}
        };
      } else if (stack === 'line') {
        try {
          delete data[key].areaStyle;
          delete data[key].stack;
        } catch (err) {}
      }
      // /堆叠图配置 结束
    }
    return data;
  },
  /* *设置图例样式 开始 */
  /* *
   * @params layerId 图层id
   */
  calgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      const item = this.graph[key];
      html += `<div>
        <div style='display:inline-block;width:40px;height:2px;background:${item.color};margin:0;padding:0;border-radius:50px;'></div>
        <div style='display:inline-block;;margin:0;padding:0;padding-left:10px;line-height:30px;'>${item.name}</div>
      </div>`;
    }
    html += '</div>';
    return html;
  },
  /* *
   * @params layerId 图层id
   */
  autoCalgraph(layerId) {
    let html = `<div style="padding:10px" class="${layerId}">`;
    for (const key in this.graph) {
      html += `<div>
        <div style = 'display:inline-block;width:40px;height:2px;background:${this.graph[key].color};margin:0;padding:0;border-radius:50px;'> </div>
        <div style='display:inline-block;;margin:0;padding:0;padding-left:10px;line-height:30px;'>${this.graph[key].name}</div>
      </div>`;
    }
    html += '</div>';
    const layers = sgisLayerBase.overLayers;
    for (const key in layers) {
      if (layers[key].layerId === layerId) {
        layers[key].html = html;
      }
    }
    // sgisLayerBase.layerControlChange();
  },
  /* *设置图例样式 结束 */
  /** 设置调整图层顺序函数*/
  setZIndexOffset(index) {
    styleModify.setZIndexOffset(index, this.layerId, this._layers);
  }
};
